package com.finna.tenant.controller;

import com.alibaba.fastjson.JSON;
import com.finna.common.utils.ResponseResult;
import com.finna.tenant.dto.PageResponse;
import com.finna.tenant.dto.TenantDTO.TenantCreateRequest;
import com.finna.tenant.dto.TenantDTO.TenantListRequest;
import com.finna.tenant.dto.TenantDTO.TenantResponse;
import com.finna.tenant.dto.TenantDTO.TenantUpdateRequest;
import com.finna.tenant.service.TenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import java.util.UUID;

/**
 * 租户控制器
 */
@RestController
@RequestMapping("/tenant")
@Tag(name = "租户接口", description = "租户信息相关接口")
public class TenantController {
    
    private static final Logger logger = LoggerFactory.getLogger(TenantController.class);
    
    @Autowired
    private TenantService tenantService;
    
    /**
     * 创建租户
     */
    @PostMapping
    @Operation(summary = "创建租户", description = "创建新租户")
    public ResponseResult<TenantResponse> addTenant(
            @Validated @RequestBody TenantCreateRequest request) {
        try {
            //TODO 从请求中获取用户ID（实际应该从认证信息中获取）
            //TODO 这里暂时使用模拟值，后续可以集成认证模块
            //TODO 从认证信息中获取用户ID
            //Long userId = getUserIdFromRequest(httpRequest);
            Long userId = 1L;
            TenantResponse response = tenantService.create(request, userId);
            logger.info("用户创建租户成功: userId={}, tenantId={}", userId, response.getId());
            logger.info("创建租户成功: 具体返回信息：{}", JSON.toJSONString(response));
            
            return ResponseResult.success(response);
        } catch (Exception e) {
            logger.error("创建租户失败: {}", e.getMessage(), e);
            return ResponseResult.error(400, "租户创建失败: " + e.getMessage());
        }
    }
    
    /**
     * 修改租户
     */
    @PutMapping("/{tenantId}")
    @Operation(summary = "修改租户", description = "修改租户信息")
    public ResponseResult<TenantResponse> modifyTenant(
            @Parameter(description = "租户ID") @PathVariable Long tenantId,
            @RequestBody TenantUpdateRequest request) {
        try {
            TenantResponse response = tenantService.update(tenantId, request);
            logger.info("修改租户成功: tenantId={}", tenantId);
            return ResponseResult.success(response);
        } catch (RuntimeException e) {
            logger.error("修改租户失败: tenantId={}, error={}", tenantId, e.getMessage());
            return ResponseResult.error(404, "租户不存在");
        } catch (Exception e) {
            logger.error("修改租户失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "租户修改失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除租户
     */
    @DeleteMapping("/{tenantId}")
    @Operation(summary = "删除租户", description = "删除租户（软删除）")
    public ResponseResult<Void> deleteTenant(
            @Parameter(description = "租户ID") @PathVariable Long tenantId) {
        try {
            tenantService.delete(tenantId);
            logger.info("删除租户成功: tenantId={}", tenantId);
            return ResponseResult.success(null);
        } catch (RuntimeException e) {
            logger.error("删除租户失败: tenantId={}, error={}", tenantId, e.getMessage());
            return ResponseResult.error(404, "租户不存在");
        } catch (Exception e) {
            logger.error("删除租户失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "租户删除失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取租户详情
     */
    @GetMapping("/{tenantId}")
    @Operation(summary = "获取租户详情", description = "根据ID获取租户详细信息")
    public ResponseResult<TenantResponse> tenantDetail(
            @Parameter(description = "租户ID") @PathVariable Long tenantId) {
        try {
            TenantResponse response = tenantService.getById(tenantId);
            return ResponseResult.success(response);
        } catch (RuntimeException e) {
            logger.error("查询租户失败: tenantId={}, error={}", tenantId, e.getMessage());
            return ResponseResult.error(404, "租户不存在");
        } catch (Exception e) {
            logger.error("查询租户失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "租户查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取租户列表（分页）
     */
    @GetMapping
    @Operation(summary = "获取租户列表", description = "分页查询租户列表，支持过滤条件")
    public ResponseResult<PageResponse<TenantResponse>> tenantList(
            @Parameter(description = "租户名称") @RequestParam(required = false) String name,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "是否管理员租户") @RequestParam(required = false) Boolean isAdmin,
            @Parameter(description = "是否公开") @RequestParam(required = false) Boolean isPublic,
            @Parameter(description = "页码") @RequestParam(required = false, defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        try {
            TenantListRequest request = new TenantListRequest();
            request.setName(name);
            request.setStatus(status);
            request.setIsAdmin(isAdmin);
            request.setIsPublic(isPublic);
            request.setPage(page);
            request.setPageSize(pageSize);
            
            PageResponse<TenantResponse> response = tenantService.list(request);
            logger.info("租户列表查询成功: page={}, pageSize={}, total={}", page, pageSize, response.getTotal());
            
            return ResponseResult.success(response);
        } catch (Exception e) {
            logger.error("租户列表查询失败: {}", e.getMessage(), e);
            return ResponseResult.error(500, "租户列表查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 从请求中获取用户ID
     * 实际应该从认证信息中获取，这里先使用模拟值
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        // TODO: 从JWT token或session中获取用户ID
        // TODO 暂时返回模拟值
        String userIdHeader = request.getHeader("X-User-Id");
        if (userIdHeader != null) {
            try {
                return Long.parseLong(userIdHeader);
            } catch (NumberFormatException e) {
                logger.warn("无效的用户ID header: {}", userIdHeader);
            }
        }
        return 1L; // 默认用户ID
    }
}